import React, { useContext, createContext, useState } from 'react';
import { loginParamsType, signinType, signoutType } from '@/pages/user/data.d'

import { loginService, logoutService } from '@/services/user'


const defaultUser = localStorage.getItem('token') ? 'user' : null



export interface createContextType {
  user: string | null;
  signin: signinType;
  signout: signoutType;
}
// 创建一个 Context 对象
// 如何设置react hooks的TS参考这里: https://juejin.cn/post/6904151074622734344
export const AuthContext = createContext<createContextType>({
  user: defaultUser,
  signin: () => {
    //
  },
  signout: () => {
    //
  },
});


export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState<string | null>(defaultUser);

  const signin = async (params: loginParamsType): Promise<boolean> => {
    let result = false;
    const res = await loginService(params)
    if (res.code === 200) {
      const userName = 'user';
      setUser(userName);
      localStorage.setItem('token', userName)
      result = true;
    }
    return result;
  };

  const signout = async (): Promise<boolean> => {
    let result = false;
    const res = await logoutService()
    if (res.code === 200) {
      setUser(null);
      localStorage.clear();
      result = true;
    }
    return result;
  };

  const defaultValue = {
    user,
    signin,
    signout
  }

  return (
    <AuthContext.Provider value={defaultValue}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}




